import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage, ElLoading } from 'element-plus'

let loading: any

const startLoading = () => {
  interface Options {
    lock: boolean;
    text: string;
    background: string;
  }
  const options: Options = {
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  }
  loading = ElLoading.service(options)
}

const endLoading = () => {
  loading.close()
}

// 创建axios实例
const service = axios.create({
  // baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000 // 请求超时时间
})

// 请求拦截
service.interceptors.request.use((config: AxiosRequestConfig) => {
  // 加载loading
  startLoading()
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// 响应拦截
service.interceptors.response.use((response: AxiosResponse<any>) => {
  // 介绍loading
  endLoading()
  return response
}, error => {
  endLoading()
  // 错误提醒
  ElMessage({
    message: error.message,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
})

export default service
